// 登录与注册的仓库
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo ,reqUserLogout} from "@/api"
import { setToken ,getToken,removeToken} from "@/utils/token"
const state = {
    code: "",
    token: getToken(),
    userInfo:{},

}

const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state,userInfo){
        state.userInfo=userInfo
    },
    CLEAR(state){
        state.token='';
        state.userInfo={};
        removeToken();
    }
}

const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        // console.log(result)
        if (result.code == 200) {
            commit("GETCODE", result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        console.log(result)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new console.error('faile'))
        }
    },
    // 登录业务
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data);
        if (result.code == 200) {
            commit("USERLOGIN", result.data.token);
            //localStorage.setItem("TOKEN",result.data.token)
            // 持久化存储token
            setToken(result.data.token);
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息
    async getUserInfo({ commit, state, dispatch }) {
        let result = await reqUserInfo();
        console.log(result)
        if (result.code == 200) {
            commit('GETUSERINFO', result.data);
            return 'ok';
        } else {
            // return Promise.reject(new Error('faile'));
        }
    },
    //退出登录的业务
    async userLogout({ commit, state, dispatch }) {
        //发请求通知服务器销毁当前token【学生证】
        let result = await reqUserLogout();
        if (result.code == 200) {
            commit('CLEAR');
            return 'ok';
        } else {
            return Promise.reject(new Error(result.message));
        }
    }
}

const getters = {}

export default {
    state, mutations, actions, getters
}